class Snake{
    head:HTMLElement;
    body:HTMLCollection;
    snakeContainer:HTMLElement;
    constructor() {
        this.snakeContainer=document.querySelector('.snakes')!;
        this.head=document.querySelector('#snake-head')!;
        this.body=this.snakeContainer.getElementsByTagName('div');
    }

    get X(){
        return this.head.offsetLeft;
    }

    get Y(){
        return this.head.offsetTop;
    }

    set X(val){
        if(this.X===val){
            return;
        }
        if(val<0 || val>290){
            throw new Error('蛇撞墙了!');
        }

        if(this.body[1] && (this.body[1] as HTMLElement).offsetLeft===val){
            console.log('蛇回头了');
            if(this.X<val){
                val=this.X-10;
            }else{
                val=this.X+10;
            }
        }
        this.checkHead();
        this.moveBody();
        this.head.style.left=val+'px';
    }

    set Y(val){
        if(this.Y===val){
            return;
        }
        if(val<0 || val>290){
            throw new Error('蛇撞墙了!');
        }
        if(this.body[1] && (this.body[1] as HTMLElement).offsetTop===val){
            console.log('蛇回头了');
            if(this.Y<val){
                val=this.Y-10;
            }else{
                val=this.Y+10;
            }
        }
        this.checkHead();
        this.moveBody();
        this.head.style.top=val+'px';
    }

    grow(){
        this.snakeContainer.insertAdjacentHTML('beforeend','<div class="snake-item"></div>');
    }

    moveBody(){
        for(let i=this.body.length-1;i>0;i--){
            let preX=(this.body[i-1] as HTMLElement).offsetLeft;
            let preY=(this.body[i-1] as HTMLElement).offsetTop;
            (this.body[i] as HTMLElement).style.left=preX+'px';
            (this.body[i] as HTMLElement).style.top=preY+'px';

        }
    }
    checkHead(){
        for(let i=1;i<this.body.length;i++){
            let bd=this.body[i] as HTMLElement;
            if(this.X===bd.offsetLeft && this.Y===bd.offsetTop){
                throw new Error('蛇撞到自己的身体了!');
            }
        }
    }
}

export default Snake;